package com.sense.feel.login.view

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.sense.feel.login.model.bean.PictureCode
import com.sense.kukoo.biz_login.R
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.lib_logger.LoggerManager


/**
 * <br> ClassName:   PictureVerifyActivity.kt
 * <br> Description: 通用WebView界面
 * <br> Author:      lionszhang
 * <br> Date:        2021/11/9
 */
const val PICTURE_VERIFY_ACTIVITY_RESULT_CODE = 1000

@Route(path = ARouterUrl.ROUTE_LOGIN_MODULE_PICTURE_VERIFY_ACTIVITY)
class PictureVerifyActivity : AppCompatActivity() {
    private var webview: WebView? = null
    private var webSettings: WebSettings? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login_activity_picture_verify)
        initView()
    }

    private fun initView() {
        webview = findViewById<View>(R.id.webview) as WebView
        webSettings = webview?.settings
        webSettings?.useWideViewPort = true
        webSettings?.loadWithOverviewMode = true
        // 禁用缓存
        webSettings?.cacheMode = WebSettings.LOAD_NO_CACHE
        webview?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }
        }
        // 开启js支持
        webSettings?.javaScriptEnabled = true
        webview?.addJavascriptInterface(JsBridge(), "jsBridge")
        webview?.loadUrl("file:///android_asset/TXPictureYanZheng.html")
    }

    internal inner class JsBridge {
        private val TAG = "JsBridge"
        @JavascriptInterface
        fun getData(data: String) {
            LoggerManager.e(TAG, "data=============$data")
            val gson = Gson()
            val pictureCode = gson.fromJson(data, PictureCode::class.java)
            if (pictureCode.ret == 0&&pictureCode.ticket.isNotEmpty()) { //赋值
                var intent = Intent()
                intent.putExtra("pictureCode", pictureCode)
                setResult(PICTURE_VERIFY_ACTIVITY_RESULT_CODE, intent)
                finish()
            } else if (pictureCode.ret == 2) { //关闭界面
                finish()
            }
        }
    }
}
